import {
  BarChartOutlined,
  DashboardOutlined,
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  EyeOutlined,
  FileTextOutlined,
  FullscreenOutlined,
  HeartOutlined,
  LineChartOutlined,
  MoreOutlined,
  PieChartOutlined,
  PlusOutlined,
  ProjectOutlined,
  ReloadOutlined,
  SettingOutlined,
  ShareAltOutlined,
  StarOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { ProCard, ProDescriptions } from "@ant-design/pro-components";
import {
  Alert,
  Avatar,
  Badge,
  Button,
  Card,
  Col,
  Collapse,
  DatePicker,
  Divider,
  Dropdown,
  Empty,
  Input,
  List,
  Menu,
  Modal,
  Pagination,
  Progress,
  Rate,
  Result,
  Row,
  Select,
  Skeleton,
  Slider,
  Space,
  Spin,
  Statistic,
  Steps,
  Switch,
  Table,
  Tabs,
  Tag,
  Timeline,
  Tooltip,
  Typography,
  message,
} from "antd";
import type { MenuProps } from "antd";

import React, { useEffect, useState } from "react";

const { Title, Paragraph, Text } = Typography;
const { TabPane } = Tabs;
const { Panel } = Collapse;
const { Step } = Steps;
const { RangePicker } = DatePicker;

interface ChartData {
  name: string;
  value: number;
  color: string;
}

interface ProjectItem {
  id: string;
  name: string;
  status: "planning" | "development" | "testing" | "completed" | "cancelled";
  priority: "low" | "medium" | "high";
  manager: string;
  progress: number;
  startDate: string;
  endDate: string;
  budget: number;
  team: string[];
}

const Page29: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [chartData, setChartData] = useState<ChartData[]>([]);
  const [projects, setProjects] = useState<ProjectItem[]>([]);
  const [selectedProject, setSelectedProject] = useState<ProjectItem | null>(
    null,
  );
  const [modalVisible, setModalVisible] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [autoRefresh, setAutoRefresh] = useState(false);
  const [rating, setRating] = useState(4);
  const [sliderValue, setSliderValue] = useState(50);

  useEffect(() => {
    // 模拟图表数据
    const mockChartData: ChartData[] = [
      { name: "前端开发", value: 35, color: "#1890ff" },
      { name: "后端开发", value: 28, color: "#52c41a" },
      { name: "UI设计", value: 22, color: "#faad14" },
      { name: "测试", value: 15, color: "#f5222d" },
    ];
    setChartData(mockChartData);

    // 模拟项目数据
    const mockProjects: ProjectItem[] = [
      {
        id: "1",
        name: "电商平台重构",
        status: "development",
        priority: "high",
        manager: "张三",
        progress: 75,
        startDate: "2024-01-01",
        endDate: "2024-06-30",
        budget: 500000,
        team: ["前端", "后端", "UI", "测试"],
      },
      {
        id: "2",
        name: "移动端APP开发",
        status: "testing",
        priority: "medium",
        manager: "李四",
        progress: 90,
        startDate: "2023-10-01",
        endDate: "2024-03-31",
        budget: 300000,
        team: ["移动端", "后端", "UI"],
      },
      {
        id: "3",
        name: "数据分析系统",
        status: "planning",
        priority: "low",
        manager: "王五",
        progress: 15,
        startDate: "2024-03-01",
        endDate: "2024-12-31",
        budget: 800000,
        team: ["数据", "后端", "前端"],
      },
    ];
    setProjects(mockProjects);
  }, []);

  // 点击事件处理函数
  const handleChartClick = (data: ChartData) => {
    message.success(`点击了图表: ${data.name} - ${data.value}%`);
  };

  const handleProjectClick = (project: ProjectItem) => {
    setSelectedProject(project);
    setModalVisible(true);
  };

  const handleStatusChange = (
    projectId: string,
    newStatus: ProjectItem["status"],
  ) => {
    setProjects((prev) =>
      prev.map((project) =>
        project.id === projectId ? { ...project, status: newStatus } : project,
      ),
    );
    message.success(`项目状态已更新为: ${newStatus}`);
  };

  const handlePriorityChange = (
    projectId: string,
    priority: ProjectItem["priority"],
  ) => {
    setProjects((prev) =>
      prev.map((project) =>
        project.id === projectId ? { ...project, priority } : project,
      ),
    );
    message.info(`优先级已更新为: ${priority}`);
  };

  const handleProgressUpdate = (projectId: string, progress: number) => {
    setProjects((prev) =>
      prev.map((project) =>
        project.id === projectId ? { ...project, progress } : project,
      ),
    );
    message.success(`进度已更新为: ${progress}%`);
  };

  const handleRefreshData = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success("数据刷新完成");
    }, 1000);
  };

  const handleExportData = () => {
    message.loading("正在导出数据...", 2).then(() => {
      message.success("数据导出成功！");
    });
  };

  const handleFullscreen = () => {
    message.info("进入全屏模式");
  };

  const handleSettings = () => {
    message.info("打开设置面板");
  };

  const handleAddProject = () => {
    message.success("添加新项目");
  };

  const handleEditProject = (project: ProjectItem) => {
    message.info(`编辑项目: ${project.name}`);
  };

  const handleDeleteProject = (project: ProjectItem) => {
    message.success(`删除项目: ${project.name}`);
    setProjects((prev) => prev.filter((p) => p.id !== project.id));
  };

  const handleShareProject = (project: ProjectItem) => {
    message.info(`分享项目: ${project.name}`);
  };

  const handleFavoriteProject = (project: ProjectItem) => {
    message.success(`收藏项目: ${project.name}`);
  };

  const handleStepChange = (current: number) => {
    setCurrentStep(current);
    message.info(`切换到步骤: ${current + 1}`);
  };

  const handleRatingChange = (value: number) => {
    setRating(value);
    message.success(`评分已更新为: ${value} 星`);
  };

  const handleSliderChange = (value: number) => {
    setSliderValue(value);
    message.info(`滑块值: ${value}`);
  };

  const handleAutoRefreshChange = (checked: boolean) => {
    setAutoRefresh(checked);
    message.success(`自动刷新已${checked ? "开启" : "关闭"}`);
  };

  const getStatusColor = (status: ProjectItem["status"]) => {
    switch (status) {
      case "completed":
        return "success";
      case "development":
        return "processing";
      case "testing":
        return "warning";
      case "planning":
        return "default";
      case "cancelled":
        return "error";
      default:
        return "default";
    }
  };

  const getPriorityColor = (priority: ProjectItem["priority"]) => {
    switch (priority) {
      case "high":
        return "red";
      case "medium":
        return "orange";
      case "low":
        return "green";
      default:
        return "default";
    }
  };

  const getStatusText = (status: ProjectItem["status"]) => {
    switch (status) {
      case "completed":
        return "已完成";
      case "development":
        return "开发中";
      case "testing":
        return "测试中";
      case "planning":
        return "规划中";
      case "cancelled":
        return "已取消";
      default:
        return status;
    }
  };

  const getPriorityText = (priority: ProjectItem["priority"]) => {
    switch (priority) {
      case "high":
        return "高";
      case "medium":
        return "中";
      case "low":
        return "低";
      default:
        return priority;
    }
  };

  const getProjectMenuItems = (project: ProjectItem): MenuProps["items"] => [
    {
      key: "edit",
      icon: <EditOutlined />,
      label: "编辑",
      onClick: () => handleEditProject(project),
    },
    {
      key: "share",
      icon: <ShareAltOutlined />,
      label: "分享",
      onClick: () => handleShareProject(project),
    },
    {
      key: "favorite",
      icon: <StarOutlined />,
      label: "收藏",
      onClick: () => handleFavoriteProject(project),
    },
    {
      type: "divider",
    },
    {
      key: "delete",
      icon: <DeleteOutlined />,
      label: "删除",
      danger: true,
      onClick: () => handleDeleteProject(project),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Title level={2}>页面 29 - 项目管理仪表板</Title>

      {/* 顶部操作栏 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col span={18}>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAddProject}
            >
              新建项目
            </Button>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefreshData}
              loading={loading}
            >
              刷新
            </Button>
            <Button icon={<DownloadOutlined />} onClick={handleExportData}>
              导出
            </Button>
            <Button icon={<FullscreenOutlined />} onClick={handleFullscreen}>
              全屏
            </Button>
            <Button icon={<SettingOutlined />} onClick={handleSettings}>
              设置
            </Button>
          </Space>
        </Col>
        <Col span={6} style={{ textAlign: "right" }}>
          <Space>
            <Text>自动刷新:</Text>
            <Switch checked={autoRefresh} onChange={handleAutoRefreshChange} />
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        {/* 统计卡片 */}
        <Col span={6}>
          <Card>
            <Statistic
              title="总项目数"
              value={projects.length}
              prefix={<Badge count={projects.length} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="完成率"
              value={
                (projects.filter((p) => p.status === "completed").length /
                  projects.length) *
                100
              }
              suffix="%"
              precision={1}
              valueStyle={{ color: "#3f8600" }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="进行中"
              value={projects.filter((p) => p.status === "development").length}
              valueStyle={{ color: "#1890ff" }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总预算"
              value={projects.reduce((sum, p) => sum + p.budget, 0)}
              suffix="元"
              valueStyle={{ color: "#faad14" }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {/* 图表区域 */}
        <Col span={12}>
          <ProCard title="项目分布" extra={<BarChartOutlined />}>
            <div
              style={{
                height: 300,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              {chartData.map((item, index) => (
                <div
                  key={item.name}
                  style={{
                    width: "25%",
                    textAlign: "center",
                    cursor: "pointer",
                    padding: "10px",
                  }}
                  onClick={() => handleChartClick(item)}
                >
                  <div
                    style={{
                      height: `${item.value * 2}px`,
                      backgroundColor: item.color,
                      borderRadius: "4px",
                      marginBottom: "8px",
                    }}
                  />
                  <div style={{ fontSize: "12px" }}>{item.name}</div>
                  <div style={{ fontSize: "16px", fontWeight: "bold" }}>
                    {item.value}%
                  </div>
                </div>
              ))}
            </div>
          </ProCard>
        </Col>

        {/* 项目列表 */}
        <Col span={12}>
          <ProCard title="项目列表" extra={<EyeOutlined />}>
            <List
              dataSource={projects}
              renderItem={(project) => (
                <List.Item
                  actions={[
                    <Dropdown
                      key="more"
                      menu={{ items: getProjectMenuItems(project) }}
                      trigger={["click"]}
                    >
                      <Button type="text" icon={<MoreOutlined />} />
                    </Dropdown>,
                  ]}
                >
                  <List.Item.Meta
                    avatar={
                      <Avatar
                        style={{
                          backgroundColor: getStatusColor(project.status),
                        }}
                      >
                        <ProjectOutlined />
                      </Avatar>
                    }
                    title={
                      <a onClick={() => handleProjectClick(project)}>
                        {project.name}
                      </a>
                    }
                    description={
                      <Space direction="vertical" size="small">
                        <Space>
                          <Tag color={getStatusColor(project.status)}>
                            {getStatusText(project.status)}
                          </Tag>
                          <Tag color={getPriorityColor(project.priority)}>
                            {getPriorityText(project.priority)}优先级
                          </Tag>
                        </Space>
                        <Progress
                          percent={project.progress}
                          size="small"
                          showInfo={false}
                        />
                        <Text type="secondary">
                          负责人: {project.manager} | 预算: ¥
                          {project.budget.toLocaleString()}
                        </Text>
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          </ProCard>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {/* 步骤流程 */}
        <Col span={8}>
          <ProCard title="项目流程">
            <Steps
              current={currentStep}
              onChange={handleStepChange}
              direction="vertical"
              size="small"
            >
              <Step title="需求分析" description="已完成" />
              <Step title="设计阶段" description="进行中" />
              <Step title="开发阶段" description="待开始" />
              <Step title="测试阶段" description="待开始" />
              <Step title="部署上线" description="待开始" />
            </Steps>
          </ProCard>
        </Col>

        {/* 交互组件 */}
        <Col span={8}>
          <ProCard title="交互组件">
            <Space direction="vertical" style={{ width: "100%" }}>
              <div>
                <Text>评分: </Text>
                <Rate value={rating} onChange={handleRatingChange} />
              </div>
              <div>
                <Text>进度: {sliderValue}%</Text>
                <Slider
                  value={sliderValue}
                  onChange={handleSliderChange}
                  style={{ marginTop: 8 }}
                />
              </div>
              <div>
                <Text>选择类型: </Text>
                <Select
                  defaultValue="option1"
                  style={{ width: 120, marginLeft: 8 }}
                  options={[
                    { value: "option1", label: "选项1" },
                    { value: "option2", label: "选项2" },
                    { value: "option3", label: "选项3" },
                  ]}
                />
              </div>
              <div>
                <Text>日期范围: </Text>
                <RangePicker style={{ marginLeft: 8 }} />
              </div>
            </Space>
          </ProCard>
        </Col>

        {/* 时间线 */}
        <Col span={8}>
          <ProCard title="项目时间线">
            <Timeline>
              <Timeline.Item color="green">
                <p>项目启动 2024-01-01</p>
              </Timeline.Item>
              <Timeline.Item color="blue">
                <p>需求评审 2024-01-15</p>
              </Timeline.Item>
              <Timeline.Item color="red">
                <p>设计完成 2024-02-01</p>
              </Timeline.Item>
              <Timeline.Item>
                <p>开发开始 2024-02-15</p>
              </Timeline.Item>
            </Timeline>
          </ProCard>
        </Col>
      </Row>

      {/* 项目详情模态框 */}
      <Modal
        title="项目详情"
        open={modalVisible}
        onOk={() => setModalVisible(false)}
        onCancel={() => setModalVisible(false)}
        width={600}
      >
        {selectedProject && (
          <ProDescriptions column={1}>
            <ProDescriptions.Item label="项目名称">
              {selectedProject.name}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="状态">
              <Tag color={getStatusColor(selectedProject.status)}>
                {getStatusText(selectedProject.status)}
              </Tag>
            </ProDescriptions.Item>
            <ProDescriptions.Item label="优先级">
              <Tag color={getPriorityColor(selectedProject.priority)}>
                {getPriorityText(selectedProject.priority)}优先级
              </Tag>
            </ProDescriptions.Item>
            <ProDescriptions.Item label="项目经理">
              {selectedProject.manager}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="进度">
              <Progress percent={selectedProject.progress} />
            </ProDescriptions.Item>
            <ProDescriptions.Item label="开始日期">
              {selectedProject.startDate}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="结束日期">
              {selectedProject.endDate}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="预算">
              ¥{selectedProject.budget.toLocaleString()}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="团队成员">
              {selectedProject.team.map((member) => (
                <Tag key={member} color="blue">
                  {member}
                </Tag>
              ))}
            </ProDescriptions.Item>
          </ProDescriptions>
        )}
      </Modal>
    </div>
  );
};

export default Page29;
